//package com.water.gateway.security;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.security.core.context.ReactiveSecurityContextHolder;
//import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
//import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
//import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//
//import reactor.core.publisher.Mono;
//
///**
// * 实现refresh_token的逻辑
// * 在请求转发到下游服务前，调用OAuth2AuthorizedClientManager.authorize()，获得（自动续期的）access_token，然后设置到转发请求的Header中。
// * 获取当前用户认证信息 → 构建OAuth2AuthorizeRequest → 调用authorize() → 拿到 token → 写入请求头 → 继续转发请求
// */
//@Component
//public class OAuth2TokenRelayFilter implements GlobalFilter, Ordered {
//    @Autowired
//    private OAuth2AuthorizedClientManager authorizedClientManager;
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, org.springframework.cloud.gateway.filter.GatewayFilterChain chain) {
//        // 获取当前登录用户的认证信息
//        return ReactiveSecurityContextHolder.getContext()
//            .map(ctx -> ctx.getAuthentication())
//            .flatMap(authentication -> {
//                // 构建授权请求
//                OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
//                        .withClientRegistrationId("your-client-registration-id")
//                        .principal(authentication)
//                        .build();
//                // 调用 authorize()，自动获取和续期 access_token
//                OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
//                String token = authorizedClient.getAccessToken().getTokenValue();
//                // 添加 token 到请求头
//                ServerWebExchange mutatedExchange = exchange.mutate()
//                        .request(r -> r.headers(headers -> headers.setBearerAuth(token)))
//                        .build();
//                // 继续过滤链
//                return chain.filter(mutatedExchange);
//            });
//    }
//
//    @Override
//    public int getOrder() {
//        return -1;
//    }
//}